/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.improvement.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Splitter;
import com.google.gson.Gson;
import com.koron.audit.approval.AfterApprovalService;
import com.koron.audit.domain.Audit;
import com.koron.audit.management.FlowManagement;
import com.koron.common.bean.StaffBean;
import com.koron.common.dfs.FastDFSClientWrapper;
import com.koron.common.domain.DataBean;
import com.koron.common.generator.DefaultIdGenerator;
import com.koron.improvement.bean.SecurityReportBean;
import com.koron.improvement.mapper.SecurityReportMapper;
import com.koron.improvement.service.api.SecurityReportService;
import com.koron.improvement.utils.BusinessCode;
import com.koron.purpose.utils.PdfFileUtil;
import com.koron.risk.bean.CorpBean;
import com.koron.risk.service.api.CorpManagementService;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.swan.bean.MessageBean;

import java.util.*;

@Service
@SuppressWarnings("deprecation")
@PropertySource({"classpath:flow.properties"})
public class SecurityReportServiceImpl implements SecurityReportService, AfterApprovalService, InitializingBean {
    private static final Logger logger = LoggerFactory.getLogger(SecurityReportServiceImpl.class);

    // 状态标记(0-草稿 1-审批中 2-审批通过)
    private final String STATUS_0 = "0";
    // 状态标记(0-草稿 1-审批中 2-审批通过)
    private final String STATUS_1 = "1";
    // 状态标记(0-草稿 1-审批中 2-审批通过)
    private final String STATUS_2 = "2";

    @Autowired
    private CorpManagementService corpManagementService;

    @Value("${security_report_template_key1}")
    private String templateKey_1;
    @Value("${security_report_template_key2}")
    private String templateKey_2;
    @Value("${security_report_template_key3}")
    private String templateKey_3;

    @Autowired
    private FlowManagement flowManagement;

    @Autowired
    private FastDFSClientWrapper fastDFSClientWrapper;

    @Autowired
    private PdfFileUtil pdfFileUtil;

    @Override
    public void editApproval(Audit audit) {

    }

    @Override
    public void discardApproval(Audit audit) {

    }

    @Override
    public void processDiscard(Audit audit) {

    }

    @Override
    public void afterPropertiesSet() throws Exception {
        flowManagement.getHandlers().put(this.getClass().getName(), new SecurityReportServiceImpl());
    }

    @Override
    public MessageBean queryForList(String corpCode, String departmentCode,
                                    String srName, String srNo, String fillDateStart, String fillDateStop,
                                    String reportTypeCode, Integer reportLevel, Integer page, Integer pageSize) {
        MessageBean<DataBean<SecurityReportBean>> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            SecurityReportMapper mapper = factory.getMapper(SecurityReportMapper.class);
            // 查询
            Map map = new HashMap();
            map.put("corpCode", corpCode);
            map.put("departmentCode", departmentCode);
            map.put("srName", srName);
            map.put("srNo", srNo);
            map.put("fillDateStart", fillDateStart);
            map.put("fillDateStop", fillDateStop);
            map.put("reportTypeCode", reportTypeCode);
            map.put("reportLevel", reportLevel);
            page = (page == null || page < 1) ? 1 : page;
            pageSize = (pageSize == null || pageSize < 1) ? 10 : pageSize;
            int pageStart = (page - 1) * pageSize;
            map.put("pageStart", pageStart);
            map.put("pageSize", pageSize);
            List<SecurityReportBean> list = mapper.queryForList(map);
            DataBean<SecurityReportBean> dataBean = new DataBean<>();
            dataBean.setList(list);
            dataBean.setPageSize(pageSize);
            dataBean.setPageNo(page);
            // 总条数
            Integer totalNumber = mapper.countQueryForList(map);
            int num = totalNumber / pageSize;
            // 总页数
            Integer totalPage = totalNumber % pageSize == 0 ? num : num + 1;
            dataBean.setTotalNumber(totalNumber);
            dataBean.setTotalPage(totalPage);
            msg.setData(dataBean);
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription(BusinessCode.SUCCESS.getDescription());
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
        }
        return msg;
    }

    @Override
    public MessageBean queryById(String id) {
        MessageBean msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), void.class);
        if (StringUtils.isEmpty(id)) {
            msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
            msg.setDescription(BusinessCode.INSUFFICIENT_PARAM.getDescription());
            return msg;
        }
        try (SessionFactory factory = new SessionFactory()) {
            SecurityReportMapper mapper = factory.getMapper(SecurityReportMapper.class);
            // 查询
            SecurityReportBean bean = mapper.queryById(id);
            if (bean == null) {
                msg.setCode(BusinessCode.EXCEPTION.getCode());
                msg.setDescription("未查到该安全报告");
            }
            msg.setData(bean);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
        }
        return msg;
    }

    @Override
    public MessageBean deleteById(String id) {
        MessageBean msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), void.class);
        if (StringUtils.isEmpty(id)) {
            msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
            msg.setDescription(BusinessCode.INSUFFICIENT_PARAM.getDescription());
            return msg;
        }
        SessionFactory factory = new SessionFactory();
        try {
            SecurityReportMapper mapper = factory.getMapper(SecurityReportMapper.class);
            SecurityReportBean bean = mapper.queryById(id);
            if (bean == null) {
                msg.setCode(BusinessCode.EXCEPTION.getCode());
                msg.setDescription("该安全报告已被删除");
                factory.close(false);
                return msg;
            } else if (STATUS_2.equals(bean.getStatus())) {// 草稿可删除和编辑，非草稿不可删除和编辑
                msg.setCode(BusinessCode.EXCEPTION.getCode());
                msg.setDescription("当前安全报告不为草稿，不能进行删除");
                factory.close(false);
                return msg;
            }
            // 根据id 删除 安全报告
            int i = mapper.deleteById(id);
            if (i != 1) {
                msg.setCode(BusinessCode.EXCEPTION.getCode());
                msg.setDescription("删除失败!");
                factory.close(false);
            }
            // 删除附件
            if (StringUtils.isNotEmpty(bean.getAccessorys())) {
                List<Map> files = JSON.parseArray(bean.getAccessorys(), Map.class);
                if (files != null && files.size() > 0) {
                    for (Map file : files) {
                        Optional.ofNullable(file.get("fileUrl")).ifPresent(url -> {
                            fastDFSClientWrapper.deleteFile(url.toString());
                        });
                        Optional.ofNullable(file.get("pdfUrl")).ifPresent(url -> {
                            fastDFSClientWrapper.deleteFile(url.toString());
                        });
                    }
                }
            }
            factory.close();
        } catch (Exception e) {
            factory.close(false);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
        }finally {
            if (null != factory){
                factory.close();
            }
        }
        return msg;
    }

    @Override
    public MessageBean insert(StaffBean user, SecurityReportBean bean, MultipartFile[] files, String status,
                              String subWaterDeparCodes, String subCompChargeBusinLeaderCode, String areaSecurityManagDeparCode,
                              String areaChargeSafetyLeaderCode, String generalManagerCode, String areaChargeLeaderCode) {
        // 参数校验
        MessageBean msg = parameterCalibration(bean);
        if (msg.getCode() != 0){
            return msg;
        }
        if (StringUtils.isEmpty(bean.getSrNo())){
            bean.setSrNo("");
        }
        SessionFactory factory = new SessionFactory();
        try {
            // 新增 附件
            String fileMsgs = saveFiles(files);
            bean.setAccessorys(fileMsgs);
            SecurityReportMapper mapper = factory.getMapper(SecurityReportMapper.class);
            Date date = new Date();
            bean.setAddUser(user.getCode());
            bean.setAddUserName(user.getName());
            bean.setAddTime(date);
            bean.setUpdateUser(user.getCode());
            bean.setUpdateUserName(user.getName());
            bean.setUpdateTime(date);
            String id = DefaultIdGenerator.getInstance().generateLongId();
            bean.setId(id);

            // 状态(0-未提交 1-审批中 2-审批通过)
            bean.setStatus(status);
            mapper.insert(bean);

            // 如果状态标记(0-草稿 1-审批中 2-审批通过) 为审批中，则启动流程
            if (STATUS_1.equals(bean.getStatus())) {
                if (StringUtils.isEmpty(subCompChargeBusinLeaderCode)) {
                    factory.close(false);
                    msg.setCode(BusinessCode.EXCEPTION.getCode());
                    msg.setDescription("下属公司业务分管领导不能为空!");
                    return msg;
                }
                Map map = new HashMap();
                map.put("subCompChargeBusinLeaderCode", subCompChargeBusinLeaderCode);
                if (bean.getReportLevel() == 1) {
                    if (StringUtils.isEmpty(areaSecurityManagDeparCode)) {
                        factory.close(false);
                        msg.setCode(BusinessCode.EXCEPTION.getCode());
                        msg.setDescription("片区安全管理部不能为空!");
                        return msg;
                    }
                    if (StringUtils.isEmpty(areaChargeSafetyLeaderCode)) {
                        factory.close(false);
                        msg.setCode(BusinessCode.EXCEPTION.getCode());
                        msg.setDescription("片区分管安全领导不能为空!");
                        return msg;
                    }
                    if (StringUtils.isEmpty(generalManagerCode)) {
                        factory.close(false);
                        msg.setCode(BusinessCode.EXCEPTION.getCode());
                        msg.setDescription("片区总经理不能为空!");
                        return msg;
                    }
                    map.put("areaSecurityManagDeparCode", areaSecurityManagDeparCode);
                    map.put("areaChargeSafetyLeaderCode", areaChargeSafetyLeaderCode);
                    map.put("generalManagerCode", generalManagerCode);
                } else if (bean.getReportLevel() == 2) {
                    if (StringUtils.isEmpty(areaSecurityManagDeparCode)) {
                        factory.close(false);
                        msg.setCode(BusinessCode.EXCEPTION.getCode());
                        msg.setDescription("片区安全管理部不能为空!");
                        return msg;
                    }
                    if (StringUtils.isEmpty(areaChargeLeaderCode)) {
                        factory.close(false);
                        msg.setCode(BusinessCode.EXCEPTION.getCode());
                        msg.setDescription("片区分管领导不能为空!");
                        return msg;
                    }
                    map.put("areaSecurityManagDeparCode", areaSecurityManagDeparCode);
                    map.put("areaChargeLeaderCode", areaChargeLeaderCode);
                } else if (bean.getReportLevel() == 3) {
                    if (StringUtils.isEmpty(areaSecurityManagDeparCode)) {
                        factory.close(false);
                        msg.setCode(BusinessCode.EXCEPTION.getCode());
                        msg.setDescription("片区安全管理部不能为空!");
                        return msg;
                    }
                    map.put("areaSecurityManagDeparCode", areaSecurityManagDeparCode);
                } else {
                    factory.close(false);
                    msg.setCode(BusinessCode.EXCEPTION.getCode());
                    msg.setDescription("报告等级只支持一二三等级");
                    return msg;
                }
                Audit audit = new Audit("安全报告", "安全报告审批", user.getName(), new Date());
                audit.setTitle("安全报告");
                audit.setDescription("安全报告(" + bean.getSrName() + ")审批");
                audit.setCorpCode(bean.getCorpCode());
                audit.setCorpName(bean.getCorpName());

                audit.setId(DefaultIdGenerator.getInstance().generateLongId());
                audit.setInitiatorCode(user.getCode());
                audit.setTarget(this.getClass().getName());
                if (bean.getReportLevel() == 1) {
                    audit.setTemplateKey(templateKey_1);
                } else if (bean.getReportLevel() == 2) {
                    audit.setTemplateKey(templateKey_2);
                } else {
                    audit.setTemplateKey(templateKey_3);
                }
                audit.setOperation(1);
                audit.setState(1);
                audit.setFlowType(1);
                audit.setFlowName("安全报告审批");
                List<String> idList = Arrays.asList(id);
                audit.setBusinessIds(new Gson().toJson(idList));
                if (!StringUtils.isEmpty(subWaterDeparCodes)) {
                    // 下属水司会签codes
                    List<String> codes = Splitter.on(",").omitEmptyStrings().trimResults().splitToList(subWaterDeparCodes);
                    StringBuffer codeStr = new StringBuffer();
                    int size = codes.size();
                    int count = 0;
                    for (String code : codes) {
                        codeStr.append("1-").append(code);
                        count++;
                        if (count < size) {
                            codeStr.append(",");
                        }
                    }
                    map.put("subWaterDeparCodes", codeStr.toString());
                } else {
                    map.put("subWaterDeparCodes", "");
                }
                // 获取公司 总经理、董事长
                MessageBean messageBean = corpManagementService.queryPerMsgByCorp(bean.getCorpCode());
                if (messageBean.getCode() == BusinessCode.SUCCESS.getCode()) {
                    CorpBean corpBean = (CorpBean) messageBean.getData();
                    map.put("generalManager", corpBean.getGeneralManager());
                    map.put("chairman", corpBean.getChairman());
                } else {
                    factory.close(false);
                    return messageBean;
                }
                if (!flowManagement.initFlow(user, audit, map)) {
                    factory.close(false);
                    msg.setCode(com.koron.hazardsource.util.BusinessCode.MESSAGE_CODE_FLOW_EXCEPTION);
                    msg.setDescription(com.koron.hazardsource.util.BusinessCode.MESSAGE_DESCRIPTION_FLOW_EXCEPTION);
                    return msg;
                }
            }
            // 关闭
            factory.close();
        } catch (Exception e) {
            factory.close(false);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
        }finally {
            if (null != factory){
                factory.close();
            }
        }
        return msg;
    }

    @Override
    public MessageBean update(StaffBean user, SecurityReportBean bean, MultipartFile[] files, String status,
                              String subWaterDeparCodes, String subCompChargeBusinLeaderCode, String areaSecurityManagDeparCode,
                              String areaChargeSafetyLeaderCode, String generalManagerCode, String areaChargeLeaderCode) {
        MessageBean<?> msg = parameterCalibration(bean);
        if (msg.getCode() != 0){
            return msg;
        }
        if (StringUtils.isEmpty(bean.getSrNo())){
            bean.setSrNo("");
        }
        SessionFactory factory = new SessionFactory();
        try {
            SecurityReportMapper mapper = factory.getMapper(SecurityReportMapper.class);
            // 根据id 查询 安全会议
            SecurityReportBean securityReportBean = mapper.queryById(bean.getId());
            if (securityReportBean == null) {
                msg.setCode(BusinessCode.EXCEPTION.getCode());
                msg.setDescription("没有获取到该安全报告");
                factory.close(false);
                return msg;
            } else if (STATUS_2.equals(securityReportBean.getStatus())) {
                msg.setCode(BusinessCode.EXCEPTION.getCode());
                msg.setDescription("该安全报告已经审批通过，不允许修改");
                factory.close(false);
                return msg;
            }
            if (!STATUS_1.equals(status)) {// 如果不为审批中，则为草稿
                bean.setStatus(STATUS_0);
            } else {
                bean.setStatus(status);
            }
            bean.setUpdateTime(new Date());
            bean.setUpdateUser(user.getCode());
            bean.setUpdateUserName(user.getName());
            String str;
            // 附件保存
            if (files != null) {
                JSONArray array;
                if (!StringUtils.isEmpty(bean.getAccessorys())) {
                    array = JSON.parseArray(bean.getAccessorys());
                } else {
                    array = new JSONArray();
                }
                JSONObject object;
                for (MultipartFile file : files) {
                    object = new JSONObject();
                    object.put("filename", file.getOriginalFilename());
                    object.put("fileUrl", fastDFSClientWrapper.uploadFile(file));
                    String filename = file.getOriginalFilename();
                    int index = filename.lastIndexOf(".");
                    String filetype = filename.substring(index + 1).toLowerCase();
                    if ("pdf".equals(filetype)) {
                        object.put("pdfUrl", object.get("fileUrl"));
                    } else {
                        object.put("pdfUrl", pdfFileUtil.getPdfUrl(file, fastDFSClientWrapper));
                    }
                    array.add(object);
                }
                str = JSON.toJSONString(array);
                bean.setAccessorys(str);
            }
            if (STATUS_1.equals(securityReportBean.getStatus())) {// 如果历史数据为审批中，则只允许修改附件信息
                mapper.updateToAccessorys(bean.getId(), bean.getAccessorys());
            } else {// 为草稿状态，可以允许修改全部信息
                mapper.update(bean);
                // 如果状态标记(0-草稿 1-审批中 2-审批通过) 为审批中，则启动流程
                if (STATUS_1.equals(bean.getStatus())) {
                    if (StringUtils.isEmpty(subCompChargeBusinLeaderCode)) {
                        factory.close(false);
                        msg.setCode(BusinessCode.EXCEPTION.getCode());
                        msg.setDescription("下属公司业务分管领导不能为空!");
                        return msg;
                    }
                    Map map = new HashMap();
                    map.put("subCompChargeBusinLeaderCode", subCompChargeBusinLeaderCode);
                    if (bean.getReportLevel() == 1) {
                        if (StringUtils.isEmpty(areaSecurityManagDeparCode)) {
                            factory.close(false);
                            msg.setCode(BusinessCode.EXCEPTION.getCode());
                            msg.setDescription("片区安全管理部不能为空!");
                            return msg;
                        }
                        if (StringUtils.isEmpty(areaChargeSafetyLeaderCode)) {
                            factory.close(false);
                            msg.setCode(BusinessCode.EXCEPTION.getCode());
                            msg.setDescription("片区分管安全领导不能为空!");
                            return msg;
                        }
                        if (StringUtils.isEmpty(generalManagerCode)) {
                            factory.close(false);
                            msg.setCode(BusinessCode.EXCEPTION.getCode());
                            msg.setDescription("片区总经理不能为空!");
                            return msg;
                        }
                        map.put("areaSecurityManagDeparCode", areaSecurityManagDeparCode);
                        map.put("areaChargeSafetyLeaderCode", areaChargeSafetyLeaderCode);
                        map.put("generalManagerCode", generalManagerCode);
                    } else if (bean.getReportLevel() == 2) {
                        if (StringUtils.isEmpty(areaSecurityManagDeparCode)) {
                            factory.close(false);
                            msg.setCode(BusinessCode.EXCEPTION.getCode());
                            msg.setDescription("片区安全管理部不能为空!");
                            return msg;
                        }
                        if (StringUtils.isEmpty(areaChargeLeaderCode)) {
                            factory.close(false);
                            msg.setCode(BusinessCode.EXCEPTION.getCode());
                            msg.setDescription("片区分管领导不能为空!");
                            return msg;
                        }
                        map.put("areaSecurityManagDeparCode", areaSecurityManagDeparCode);
                        map.put("areaChargeLeaderCode", areaChargeLeaderCode);
                    } else if (bean.getReportLevel() == 3) {
                        if (StringUtils.isEmpty(areaSecurityManagDeparCode)) {
                            factory.close(false);
                            msg.setCode(BusinessCode.EXCEPTION.getCode());
                            msg.setDescription("片区安全管理部不能为空!");
                            return msg;
                        }
                        map.put("areaSecurityManagDeparCode", areaSecurityManagDeparCode);
                    } else {
                        factory.close(false);
                        msg.setCode(BusinessCode.EXCEPTION.getCode());
                        msg.setDescription("报告等级只支持一二三等级");
                        return msg;
                    }
                    Audit audit = new Audit("安全报告", "安全报告审批", user.getName(), new Date());
                    audit.setTitle("安全报告");
                    audit.setDescription("安全报告(" + bean.getSrName() + ")审批");
                    audit.setCorpCode(bean.getCorpCode());
                    audit.setCorpName(bean.getCorpName());

                    audit.setId(DefaultIdGenerator.getInstance().generateLongId());
                    audit.setInitiatorCode(user.getCode());
                    audit.setTarget(this.getClass().getName());
                    if (bean.getReportLevel() == 1) {
                        audit.setTemplateKey(templateKey_1);
                    } else if (bean.getReportLevel() == 2) {
                        audit.setTemplateKey(templateKey_2);
                    } else {
                        audit.setTemplateKey(templateKey_3);
                    }
                    audit.setOperation(1);
                    audit.setState(1);
                    audit.setFlowType(1);
                    audit.setFlowName("安全报告审批");
                    List<String> idList = Arrays.asList(bean.getId());
                    audit.setBusinessIds(new Gson().toJson(idList));
                    if (!StringUtils.isEmpty(subWaterDeparCodes)) {
                        // 下属水司会签codes
                        List<String> codes = Splitter.on(",").omitEmptyStrings().trimResults().splitToList(subWaterDeparCodes);
                        StringBuffer codeStr = new StringBuffer();
                        int size = codes.size();
                        int count = 0;
                        for (String code : codes) {
                            codeStr.append("1-").append(code);
                            count++;
                            if (count < size) {
                                codeStr.append(",");
                            }
                        }
                        map.put("subWaterDeparCodes", codeStr.toString());
                    } else {
                        map.put("subWaterDeparCodes", "");
                    }
                    // 获取公司 总经理、董事长
                    MessageBean messageBean = corpManagementService.queryPerMsgByCorp(bean.getCorpCode());
                    if (messageBean.getCode() == BusinessCode.SUCCESS.getCode()) {
                        CorpBean corpBean = (CorpBean) messageBean.getData();
                        map.put("generalManager", corpBean.getGeneralManager());
                        map.put("chairman", corpBean.getChairman());
                    } else {
                        factory.close(false);
                        return messageBean;
                    }
                    if (!flowManagement.initFlow(user, audit, map)) {
                        factory.close(false);
                        msg.setCode(com.koron.hazardsource.util.BusinessCode.MESSAGE_CODE_FLOW_EXCEPTION);
                        msg.setDescription(com.koron.hazardsource.util.BusinessCode.MESSAGE_DESCRIPTION_FLOW_EXCEPTION);
                        return msg;
                    }
                }
            }
            // 删除附件
            String accessorysStr = securityReportBean.getAccessorys();
            if (!StringUtils.isEmpty(accessorysStr)) {
                List<Map> meetingRecords_old = JSON.parseArray(accessorysStr, Map.class);
                List<Map> meetingRecords_new;
                if (!StringUtils.isEmpty(bean.getAccessorys())) {
                    meetingRecords_new = JSON.parseArray(bean.getAccessorys(), Map.class);
                } else {
                    meetingRecords_new = new ArrayList<>();
                }
                for (Map map : meetingRecords_old) {
                    if (!filter(map, meetingRecords_new, "fileUrl")) {// 不存在:删除文件
                        Optional.ofNullable(map.get("fileUrl")).ifPresent(u -> {
                            if (!StringUtils.isEmpty(u.toString())) {
                                fastDFSClientWrapper.deleteFile(u.toString());
                            }
                        });
                        Optional.ofNullable(map.get("pdfUrl")).ifPresent(u -> {
                            if (!StringUtils.isEmpty(u.toString())) {
                                fastDFSClientWrapper.deleteFile(u.toString());
                            }
                        });
                    }
                }
            }
            factory.close();
        } catch (Exception e) {
            factory.close(false);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
        }finally {
            if (null != factory){
                factory.close();
            }
        }
        return msg;
    }

    /**
     * 判断map中的 key是否在list中存在
     *
     * @param map
     * @param list
     * @param key
     * @return
     */
    private boolean filter(Map<String, String> map, List<Map> list, String key) {
        String str = map.get(key);
        if (StringUtils.isEmpty(str)) {
            return false;
        }
        if (list == null || list.size() == 0) {
            return false;
        }
        for (Map m : list) {
            if (str.equals(Optional.ofNullable(m.get(key)).get().toString())) {
                return true;
            }
        }
        return false;
    }

    /**
     * 参数校验
     *
     * @param bean
     * @return
     */
    private MessageBean parameterCalibration(SecurityReportBean bean) {
        MessageBean msg = MessageBean.create(0, BusinessCode.SUCCESS.getDescription(), void.class);
        if (StringUtils.isEmpty(bean.getCorpCode()) || StringUtils.isEmpty(bean.getCorpName())
                || StringUtils.isEmpty(bean.getDepartmentCode()) || StringUtils.isEmpty(bean.getDepartmentName())
                || StringUtils.isEmpty(bean.getSrName()) || bean.getFillDate() == null || StringUtils.isEmpty(bean.getReportTypeCode())
                || StringUtils.isEmpty(bean.getReportType()) || StringUtils.isEmpty(bean.getSrNo())
                || StringUtils.isEmpty(bean.getSrName()) || bean.getReportLevel() == null) {
            msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
            msg.setDescription(BusinessCode.INSUFFICIENT_PARAM.getDescription());
        }
        return msg;
    }

    /**
     * 保存附件
     *
     * @param files
     * @return 返回附件信息json数据格式
     */
    private String saveFiles(MultipartFile[] files) throws Exception {
        if (files == null || files.length == 0) {
            return null;
        }
        JSONArray array = new JSONArray();
        JSONObject object;
        for (MultipartFile file : files) {
            object = new JSONObject();
            object.put("filename", file.getOriginalFilename());
            object.put("fileUrl", fastDFSClientWrapper.uploadFile(file));
            String filename = file.getOriginalFilename();
            int index = filename.lastIndexOf(".");
            String filetype = filename.substring(index + 1).toLowerCase();
            if ("pdf".equals(filetype)) {
                object.put("pdfUrl", object.get("fileUrl"));
            } else {
                object.put("pdfUrl", pdfFileUtil.getPdfUrl(file, fastDFSClientWrapper));
            }
            array.add(object);
        }
        return JSON.toJSONString(array);
    }

    @Override
    public void reject(Audit audit, List<String> userIdList) {
        // TODO 流程驳回操作
    }

    @Override
    public void passApproval(Integer operation, Audit audit) {
        // TODO 流程提交成功操作
    }
}
